﻿--[[
   @brief    model for friend message
   @author   vincentlao
   @version  1.0
   @date     2015-06-26
--]]

friend_message_model =
{
    ierd_tgp.tpf_ui.Require("social\\friend_list\\model.lua");

    friend_message_= {};
    MAX_FRIEND_MESSAGE = 300;

    message_sort_func = function(a, b)
        local a_msg_time = a.time;
        local b_msg_time = b.time; 
        if a_msg_time == nil then
            return false;
        end

        if b_msg_time == nil then
            return true;
        end

        return (a_msg_time > b_msg_time);
    end;

    init = function()
        ierd_tgp.tpf_ui.Log("[friend_message_model]init");
        friend_message_model.friend_message_= {};
    end;

    uninit = function()
        ierd_tgp.tpf_ui.Log("[friend_message_model]uninit");
    end;
    
    add_message = function(message)
      if friend_message_model.friend_message_[message.friend_id] == nil then
        friend_message_model.friend_message_[message.friend_id] = {};
      end

      if #friend_message_model.friend_message_[message.friend_id] > friend_message_model.MAX_FRIEND_MESSAGE then
          table.remove(friend_message_model.friend_message_[message.friend_id], #friend_message_model.friend_message_[message.friend_id]);
      end

      table.insert(friend_message_model.friend_message_[message.friend_id], 1, message);
    end;

    get_friend_messages = function(friend_id)
        if friend_message_model.friend_message_[friend_id] == nil then
            friend_message_model.friend_message_[friend_id] = {};
        end
        
        return friend_message_model.friend_message_[friend_id];
    end;

    clear_all_friend_messages = function()
        friend_message_model.friend_message_ = {};
    end;

    clear_friend_messages = function(friend_id)
        if friend_message_model.friend_message_[friend_id] == nil then
            return;
        end

        if #friend_message_model.friend_message_[friend_id] == 0 then
            return;
        end

        friend_message_model.friend_message_[friend_id] = {};
        --friend_message_model.fire_friend_clear_message_event(friend_id);
    end;

    get_message_count = function(friend_id)
        if friend_message_model.friend_message_[friend_id] == nill then
          return 0;
        end

        return #friend_message_model.friend_message_[friend_id];
    end;

    get_friend_last_message = function(friend_id)
        local friend_messages = friend_message_model.friend_message_[friend_id];
        if friend_messages == nil or #friend_messages == 0 then
            return nil;
        end

        return friend_messages[1];  
    end;
};

friend_message_model.init();
